package hust.music.dao.base;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 * JpaDaoBase
 * 
 * @author Administrator
 * @since 1.0
 */
public class JpaDaoBase implements JpaDao {

	protected EntityManager entityManager;

	@Override
	public <T> void save(T t) {
		entityManager.persist(t);
	}

	@Override
	public <T> void delete(T t) {
		entityManager.remove(t);
	}

	@Override
	public <T> void delete(Class<T> entityClass, Integer id) {
		entityManager.remove(get(entityClass, id));
	}

	@Override
	public <T> void update(T t) {
		entityManager.merge(t);
	}

	@Override
	public <T> T get(Class<T> entityClass, Integer id) {
		return entityManager.find(entityClass, id);
	}

	@Override
	public <T> List<T> findAll(Class<T> entityClass, String jpql) {
		return entityManager.createQuery(jpql, entityClass).getResultList();
	}

	@Override
	public <T> List<T> findAll(Class<T> entityClass, String jpql, Object param) {
		return entityManager.createQuery(jpql, entityClass).setParameter(0,
				param).getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> findAll(Class<T> entityClass, String jpql,
			Object[] params) {
		Query query = entityManager.createQuery(jpql, entityClass);
		for (int i = 0; i < params.length; i++) {
			query = query.setParameter(i, params[i]);
		}
		return query.getResultList();
	}

	@Override
	public <T> List<T> findByPage(Class<T> entityClass, String jpql,
			int firstResult, int maxResult) {
		return entityManager.createQuery(jpql, entityClass).setFirstResult(
				firstResult).setMaxResults(maxResult).getResultList();
	}

	@Override
	public <T> List<T> findByPage(Class<T> entityClass, String jpql,
			Object param, int firstResult, int maxResult) {
		return entityManager.createQuery(jpql, entityClass).setParameter(0,
				param).setFirstResult(firstResult).setMaxResults(maxResult)
				.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> findByPage(Class<T> entityClass, String jpql,
			Object[] params, int firstResult, int maxResult) {
		Query query = entityManager.createQuery(jpql, entityClass);
		for (int i = 0; i < params.length; i++) {
			query = query.setParameter(i, params[i]);
		}
		return query.setFirstResult(firstResult).setMaxResults(maxResult)
				.getResultList();
	}

}
